﻿layui.use(['form', 'dtree', 'http', 'popup'], function () {
    var form = layui.form;
    var dtree = layui.dtree;
    var http = layui.http;
    var popup = layui.popup;
    var $ = layui.$;
    dtree.render({
        elem: "#tree",
        initLevel: "2",
        type: "all",
        line: true,
        ficon: ["1", "-1"],
        icon: ["0", "2"],
        method: 'get',
        dataStyle: 'layuiStyle',
        response: { message: "msg", statusCode: 0 },
        url: '/Classification/GetTree'
    });
    dtree.on("node('tree')", function (obj) {
        if (obj.param.nodeId === '0') {
            $("#addSibling").attr("disabled", true);
            $(".layui-form")[0].reset();
            $("#id").val(obj.param.nodeId);
            $("#parentId").val(obj.param.nodeId);
            $("#parentName").val(obj.param.context);
        } else {
            form.val("form", obj.param.basicData);
            $("#addSibling").attr("disabled", false);
        }
    });
    $("#addSibling").click(function () {
        var param = dtree.getNowParam('tree');
        param = dtree.getParam('tree', param.parentId);
        $("#parentId").val(param.nodeId);
        $("#parentName").val(param.context);
        $("#id").val('0');
        $("#code").val('');
        $("#name").val('');
        $("#sort").val('');
    });
    $("#addChild").click(function () {
        var param = dtree.getNowParam('tree');
        $("#parentId").val(param.nodeId);
        $("#parentName").val(param.context);
        $("#id").val('0');
        $("#code").val('');
        $("#name").val('');
        $("#sort").val('');
    });
    $("#delete").click(function () {
        layer.confirm('确定删除吗?，这将删除所有子集数据。', { icon: 3, title: '提示' }, function (index) {


            layer.close(index);
        });
    });
    form.on('submit(submit)', function (data) {
        var loading = layer.load(2);
        var spreadId = $("#parentId").val();
        http.ajax({
            url: '/Classification/AddOrUpdate',
            data: data.field,
            success: function (res) {
                layer.close(loading);
                if (res.code === 0) {
                    popup.toastSuccess(res.msg);
                    $("#code").val('');
                    $("#name").val('');
                    $("#sort").val('');
                    dtree.reload("tree", {
                        request: { spreadId: spreadId },
                        done: function (tres, $ul, first) {
                            if (first) {
                                dtree.dataInit("tree", res.data);
                            }
                        }
                    });
                } else {
                    popup.toastError(res.msg);
                }
            },
            error: function () {
                layer.close(loading);
                popup.toastError("请求失败，请稍后重试");
            }
        });
        return false;
    })
});